package com.lv.service.ui

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.TipsCancel2Dialog
import com.lv.common.imp.OnDialogListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.service.R
import com.lv.service.bean.AddressDetailsBean
import com.lv.service.databinding.ActivityAddressCommonBinding
import com.lv.service.dialog.AddressFourPopupView
import com.lv.service.room.address.LocationNewReceiptAddressDbHelper
import com.lv.service.room.address.ReceiptAddressItem
import com.lv.service.utils.YgxToolsKt
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition

/**
 * 作者： ygx
 * 创建日期：2023/5/6 1:35 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：公共输入页面
 */
@Route(path = ARoutUtils.AddressCommonActivity)
class AddressCommonActivity : BaseActivity<ActivityAddressCommonBinding>(),
    View.OnClickListener {
    @Autowired(name = "title")//标题
    @JvmField
    var mTitle: String = ""

    @Autowired(name = "province")
    @JvmField
    var mProvince: String = ""

    @Autowired(name = "city")
    @JvmField
    var mCity: String = ""

    @Autowired(name = "area")
    @JvmField
    var mArea: String = ""

    @Autowired(name = "town")
    @JvmField
    var mTown: String = ""

    @Autowired(name = "content")//内容
    @JvmField
    var mContent: String = ""

    @Autowired(name = "hint")//提示
    @JvmField
    var mHint: String = ""

    @Autowired(name = "length")//content长度
    @JvmField
    var mLength: Int = -1

    @Autowired(name = "dec")//描述
    @JvmField
    var mDec: String = ""

    @Autowired(name = "subitText")//提交文字
    @JvmField
    var mSubitText: String = "保存"

    @Autowired(name = "address")
    @JvmField
    var mAddressList: ArrayList<AddressDetailsBean>? = null

    @Autowired(name = "showdialog")
    @JvmField
    var mShowDialog: Boolean = false


    @Autowired(name = "inputState")
    @JvmField
    var ADDRESS_STATE: ADDRESS_ENUM? = ADDRESS_ENUM.FOUR

    private var mUpdataAll = "0" //是否覆盖全部
    private val mAddressBeans = mutableListOf<ReceiptAddressItem>()
    private var currentProvin: Int = -1
    private var currentCity: Int = 0
    private var currentArea: Int = 0
    private var currentTown: Int = 0
    private var mAddressSelect: String = ""

    private var mProvinceFrist: String = ""
    private var mCityFrist: String = ""
    private var mAreaFrist: String = ""
    private var mTownFrist: String = ""
    private var mDetailsFrist: String = ""

    private var mProvinceFactory: String = ""
    private var mCityFactory: String = ""
    private var mAreaFactory: String = ""
    private var mTownFactory: String = ""
    private var mDetailsFactory: String = ""

    private var mProvinceStore: String = ""
    private var mCityStore: String = ""
    private var mAreaStore: String = ""
    private var mTownStore: String = ""
    private var mDetailsStore: String = ""

    override fun getLayoutRes() = R.layout.activity_address_common
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@AddressCommonActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            initSingleClickListener(
                tvSumbit, tvAddress, tvAddressFactory,
                tvAddressStore, ivLocation, ivLocationFactory, ivLocationStore
            )
        }
    }


    override fun initConfig() {
        super.initConfig()
        mBinding.titleBar.setTitle(mTitle)
        if (mHint.isEmpty()) {
            mHint = "请输入$mTitle"
        }

        if (mAddressList == null) {
            mProvinceFrist = mProvince
            mCityFrist = mCity
            mAreaFrist = mArea
            mTownFrist = mTown
            mDetailsFrist = mContent
            if (mProvince.isEmpty() || mCity.isEmpty() || mArea.isEmpty() || mTown.isEmpty()) {
                mContent = ""
                mAddressSelect = ""
            } else {
                mAddressSelect = "$mProvince$mCity$mArea$mTown"
                mBinding.ivLocation.LoadSrc(com.lv.common.R.drawable.icon_x_delete)
            }
            mBinding.addressSelect = mAddressSelect
            if (mDetailsFrist.isNotEmpty()) {
                mBinding.tvSumbitText.alpha = 1.0f
                mBinding.tvSumbit.isEnabled = true
                mBinding.etContent.setText(mDetailsFrist)
            } else {
                mBinding.tvSumbitText.alpha = 0.2f
                mBinding.tvSumbit.isEnabled = false
            }
            mBinding.clAddressFactory.visibility = View.GONE
            mBinding.clAddressStore.visibility = View.GONE
        } else if (mAddressList.isNullOrEmpty()) {
            mBinding.tvSumbitText.alpha = 0.2f
            mBinding.tvSumbit.isEnabled = false
            mBinding.clAddressFactory.visibility = View.VISIBLE
            mBinding.clAddressStore.visibility = View.VISIBLE
        } else {
            mBinding.clAddressFactory.visibility = View.VISIBLE
            mBinding.clAddressStore.visibility = View.VISIBLE
            mAddressList?.forEach { item ->
                setAddressItem(item)
            }
        }
        mBinding.etContent.hint = mHint
        mBinding.etContentStore.hint = mHint
        mBinding.etContentFactory.hint = mHint

//        mBinding.tvDec.hint = mDec
        mBinding.tvSumbitText.text = mSubitText

        if (mLength != -1) {
            mBinding.etContent.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(mLength))
            mBinding.etContentStore.filters =
                arrayOf<InputFilter>(InputFilter.LengthFilter(mLength))
            mBinding.etContentFactory.filters =
                arrayOf<InputFilter>(InputFilter.LengthFilter(mLength))
        }

//        when (ADDRESS_STATE) {
//            ADDRESS_ENUM.TWO -> {
//                mBinding.etContent.maxLines = 1
//                mBinding.etContent.ellipsize = TextUtils.TruncateAt.END
//
//            }
//            ADDRESS_ENUM.FOUR -> {
//                mBinding.etContent.inputType = InputType.TYPE_CLASS_NUMBER
//            }
//
//            else -> {
//
//            }
//
//        }
    }

    private fun setAddressItem(addressDetailsBean: AddressDetailsBean) {
        val type = addressDetailsBean.type
        when (type) {
            "0" -> {
                mProvinceFrist = addressDetailsBean.province ?: ""
                mCityFrist = addressDetailsBean.city ?: ""
                mAreaFrist = addressDetailsBean.area ?: ""
                mTownFrist = addressDetailsBean.prefecture ?: ""
                mDetailsFrist = addressDetailsBean.address ?: ""
                if (mProvinceFrist.isEmpty() || mCityFrist.isEmpty() || mAreaFrist.isEmpty() || mTownFrist.isEmpty()) {
                    mAddressSelect = ""
                } else {
                    mAddressSelect = "$mProvinceFrist$mCityFrist$mAreaFrist$mTownFrist"
                    mBinding.ivLocation.LoadSrc(com.lv.common.R.drawable.icon_x_delete)
                }
                mBinding.addressSelect = mAddressSelect
                if (mDetailsFrist.isNotEmpty()) {
                    mBinding.tvSumbitText.alpha = 1.0f
                    mBinding.tvSumbit.isEnabled = true
                    mBinding.etContent.setText(mDetailsFrist)
                } else {
                    mBinding.tvSumbitText.alpha = 0.2f
                    mBinding.tvSumbit.isEnabled = false
                }
            }

            "1" -> {
                mProvinceFactory = addressDetailsBean.province ?: ""
                mCityFactory = addressDetailsBean.city ?: ""
                mAreaFactory = addressDetailsBean.area ?: ""
                mTownFactory = addressDetailsBean.prefecture ?: ""
                mDetailsFactory = addressDetailsBean.address ?: ""
                var addressFactorySelect = ""
                if (mProvinceFactory.isEmpty() || mCityFactory.isEmpty() || mAreaFactory.isEmpty() || mTownFactory.isEmpty()) {
                    addressFactorySelect = ""
                } else {
                    addressFactorySelect =
                        "$mProvinceFactory$mCityFactory$mAreaFactory$mTownFactory"
                    mBinding.ivLocationFactory.LoadSrc(com.lv.common.R.drawable.icon_x_delete)
                }
                mBinding.addressSelectFactory = addressFactorySelect
                mBinding.etContentFactory.setText(mDetailsFactory)
            }

            "2" -> {
                mProvinceStore = addressDetailsBean.province ?: ""
                mCityStore = addressDetailsBean.city ?: ""
                mAreaStore = addressDetailsBean.area ?: ""
                mTownStore = addressDetailsBean.prefecture ?: ""
                mDetailsStore = addressDetailsBean.address ?: ""

                var addressStoreSelect = ""
                if (mProvinceStore.isEmpty() || mCityStore.isEmpty() || mAreaStore.isEmpty() || mTownStore.isEmpty()) {
                    addressStoreSelect = ""
                } else {
                    addressStoreSelect = "$mProvinceStore$mCityStore$mAreaStore$mTownStore"
                    mBinding.ivLocationStore.LoadSrc(com.lv.common.R.drawable.icon_x_delete)
                }
                mBinding.addressSelectStore = addressStoreSelect
                mBinding.etContentStore.setText(mDetailsStore)
            }
        }
    }

    override fun initData() {
        super.initData()
        //所有城市
        LocationNewReceiptAddressDbHelper.getLiveAllLocation(this@AddressCommonActivity)
            .observeKt { datas ->
                datas?.let {
                    mAddressBeans.addAll(datas)
                }
            }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.etContent.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//                if (INPUT_STATE == INPUT_ENUM.PHONE || INPUT_STATE == INPUT_ENUM.SINGLE) {
//                    if (s != null && s.isNotEmpty()) {
//                        mBinding.ivClear.visibility = View.VISIBLE
//                    } else {
//                        mBinding.ivClear.visibility = View.GONE
//                    }
//                }
                if (s != null && s.isNotEmpty() && mProvinceFrist.isNotEmpty()) {
                    mBinding.tvSumbitText.alpha = 1.0f
                    mBinding.tvSumbit.isEnabled = true
                    mDetailsFrist = s.toString()
                } else {
                    mBinding.tvSumbitText.alpha = 0.2f
                    mBinding.tvSumbit.isEnabled = false
                    mDetailsFrist = ""
                }

            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_address -> {
                switchAddress(0)
            }

            R.id.tv_address_factory -> {
                switchAddress(1)
            }

            R.id.tv_address_store -> {
                switchAddress(2)
            }

            R.id.iv_location -> {
                mProvinceFrist = ""
                mCityFrist = ""
                mAreaFrist = ""
                mTownFrist = ""
                mDetailsFrist = ""
                mBinding.ivLocation.LoadSrc(com.lv.common.R.drawable.icon_location_black_1)
                mBinding.addressSelect = ""
                mBinding.tvSumbitText.alpha = 0.2f
                mBinding.tvSumbit.isEnabled = false
                mBinding.etContent.setText("")
            }

            R.id.iv_location_factory -> {
                mProvinceFactory = ""
                mCityFactory = ""
                mAreaFactory = ""
                mTownFactory = ""
                mDetailsFactory = ""
                mBinding.ivLocationFactory.LoadSrc(com.lv.common.R.drawable.icon_location_black_1)
                mBinding.addressSelectFactory = ""
                mBinding.etContentFactory.setText("")
            }

            R.id.iv_location_store -> {
                mProvinceStore = ""
                mCityStore = ""
                mAreaStore = ""
                mTownStore = ""
                mDetailsStore = ""
                mBinding.ivLocationStore.LoadSrc(com.lv.common.R.drawable.icon_location_black_1)
                mBinding.addressSelectStore = ""
                mBinding.etContentStore.setText("")
            }

            R.id.tv_sumbit -> {
                if (mShowDialog) {
                    showHintDialog()
                } else {
                    closeSendData()
                }

            }

        }
    }

    private var mHintDialog: TipsCancel2Dialog? = null
    private fun showHintDialog() {
        mHintDialog = TipsCancel2Dialog(
            this,
            "是否覆盖所有分类下的地址信息？",
            true, true, object : OnDialogListener {
                override fun onSureClick(content: String?) {
                    mUpdataAll = "1"
                    closeSendData()
                }

                override fun onCancelClick() {
                    mUpdataAll = "0"
                    closeSendData()
                }
            })
        mHintDialog?.show()
        mHintDialog?.setConfrimText("覆盖")
        mHintDialog?.setCancelText("不覆盖")
    }

    //关闭页面，并返回数据
    private fun closeSendData() {
        mDetailsFrist = mBinding.etContent.text.toString().trim()
        mDetailsFactory = mBinding.etContentFactory.text.toString().trim()
        mDetailsStore = mBinding.etContentStore.text.toString().trim()
        intent.putExtra("province_frist", mProvinceFrist)
        intent.putExtra("city_frist", mCityFrist)
        intent.putExtra("area_frist", mAreaFrist)
        intent.putExtra("town_frist", mTownFrist)
        intent.putExtra("detail_frist", mDetailsFrist)
        intent.putExtra("province_factory", mProvinceFactory)
        intent.putExtra("city_factory", mCityFactory)
        intent.putExtra("area_factory", mAreaFactory)
        intent.putExtra("town_factory", mTownFactory)
        intent.putExtra("detail_factory", mDetailsFactory)
        intent.putExtra("province_store", mProvinceStore)
        intent.putExtra("city_store", mCityStore)
        intent.putExtra("area_store", mAreaStore)
        intent.putExtra("town_store", mTownStore)
        intent.putExtra("detail_store", mDetailsStore)
        intent.putExtra("type", mUpdataAll)

        setResult(RESULT_OK, intent)
        finish()
    }

    private fun switchAddress(i: Int) {
        currentProvin = -1
        when (i) {
            0 -> {
                mProvince = mProvinceFrist
                mCity = mCityFrist
                mArea = mAreaFrist
                mTown = mTownFrist
                mContent = mDetailsFrist
            }

            1 -> {
                mProvince = mProvinceFactory
                mCity = mCityFactory
                mArea = mAreaFactory
                mTown = mTownFactory
                mContent = mDetailsFactory
            }

            2 -> {
                mProvince = mProvinceStore
                mCity = mCityStore
                mArea = mAreaStore
                mTown = mTownStore
                mContent = mDetailsStore
            }

        }
        initAddressPop()
        showAddressSelector(i)
    }

    /**
     * 四级地址选择器
     */
    private fun showAddressSelector(positionPop: Int) {
        if (mAddressBeans.isEmpty()) {
            YgxToolsKt.doWorkManager(this, "1")
            return showToast("数据初始化,请稍候重试……")
        }
        initAddressPop()
        val mPopupView =
            AddressFourPopupView(
                this@AddressCommonActivity,
                mAddressBeans, currentProvin, currentCity, currentArea, currentTown
            ) { position, position1, position2, position3 ->
                currentProvin = position
                currentCity = position1
                currentArea = position2
                currentTown = position3
                mProvince = mAddressBeans[currentProvin].name ?: ""
                mCity =
                    mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.name
                        ?: ""
                mArea =
                    mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.telThirdCategories?.get(
                        currentArea
                    )?.name
                        ?: ""
                mTown =
                    mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.telThirdCategories?.get(
                        currentArea
                    )?.telFourCategories?.get(currentTown)?.name
                        ?: ""
                mAddressSelect =
                    "${mProvince}$mCity$mArea$mTown"
                when (positionPop) {
                    0 -> {
                        mBinding.addressSelect = mAddressSelect
                        mProvinceFrist = mProvince
                        mCityFrist = mCity
                        mAreaFrist = mArea
                        mTownFrist = mTown
                        mBinding.ivLocation.LoadSrc(com.lv.common.R.drawable.icon_x_delete)
                    }

                    1 -> {
                        mBinding.addressSelectFactory = mAddressSelect
                        mProvinceFactory = mProvince
                        mCityFactory = mCity
                        mAreaFactory = mArea
                        mTownFactory = mTown
                        mBinding.ivLocationFactory.LoadSrc(com.lv.common.R.drawable.icon_x_delete)
                    }

                    2 -> {
                        mBinding.addressSelectStore = mAddressSelect
                        mProvinceStore = mProvince
                        mCityStore = mCity
                        mAreaStore = mArea
                        mTownStore = mTown
                        mBinding.ivLocationStore.LoadSrc(com.lv.common.R.drawable.icon_x_delete)

                    }

                }
                if (mDetailsFrist.isNotEmpty() && mProvinceFrist.isNotEmpty()) {
                    mBinding.tvSumbitText.alpha = 1.0f
                    mBinding.tvSumbit.isEnabled = true
                } else {
                    mBinding.tvSumbitText.alpha = 0.2f
                    mBinding.tvSumbit.isEnabled = false
                }
//                    mEditorViewModel.obAddress.set(addressSelect)
//                    mCompany?.address = addressSelect
//                    mBinding.itemRoot = mCompany
            }
        XPopup.Builder(this@AddressCommonActivity)
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()
    }

    private fun initAddressPop() {
//        if (mProvince.isEmpty()) {
//            mProvince = mAddressBeans[0].name
//            mCity = mAddressBeans[0].telSecondCategories[0].name
//            mArea = mAddressBeans[0].telSecondCategories[0].telThirdCategories[0].name
//        }
        if (currentProvin == -1 && mProvince.isNotEmpty()) {
            var showProvin = false
            for (i in 0 until mAddressBeans.size) {
                val name = mAddressBeans[i].name ?: "全部"
                if (mProvince.isNotEmpty() && (mProvince.contains(name) || name.contains(mProvince))) {
                    currentProvin = i
                    showProvin = true
                    mAddressBeans[i].isShow = true
                    break
                }
            }
            if (!showProvin) {
                setAddressDefault()
                return
            }
//            val provinP = if (currentProvin == -1) 0 else currentProvin
//            currentProvin = if (currentProvin == -1) 0 else currentProvin

            val telSecondCategories = mAddressBeans[currentProvin].telSecondCategories
            var showCity = false
            telSecondCategories?.let {
                for (i in telSecondCategories.indices) {
                    val name = telSecondCategories[i].name ?: "全部"
                    if (mCity.isNotEmpty() && (mCity.contains(name) || name.contains(mCity))) {
                        currentCity = i
                        showCity = true
                        mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.isShow =
                            true
                        break
                    }
                }
                if (!showCity) {
                    setAddressDefault()
                    return
                }
            }
            val thirdBeans =
                mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.telThirdCategories
            var showArea = false

            thirdBeans?.let {

                for (i in thirdBeans.indices) {
                    val name = thirdBeans[i].name ?: "全部"
                    if (mArea.isNotEmpty() && (mArea.contains(name) || name.contains(mArea))) {
                        currentArea = i
                        showArea = true
                        mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.telThirdCategories?.get(
                            currentArea
                        )?.isShow =
                            true
                        break
                    }
                }
                if (!showArea) {
                    setAddressDefault()
                    return
                }
            }

            val fourBeans =
                mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.telThirdCategories?.get(
                    currentArea
                )?.telFourCategories
            var showTown = false
            fourBeans?.let {
                for (i in fourBeans.indices) {
                    val name = fourBeans[i].name ?: "全部"
                    if (mTown.isNotEmpty() && (mTown.contains(name) || name.contains(mTown))) {
                        currentTown = i
                        showTown = true
                        mAddressBeans[currentProvin].telSecondCategories?.get(currentCity)?.telThirdCategories?.get(
                            currentArea
                        )?.telFourCategories?.get(currentTown)?.isShow =
                            true

                        break
                    }
                }
                if (!showTown) {
                    setAddressDefault()
                    return
                }
            }

        }
    }

    private fun setAddressDefault() {
        currentProvin = -1
        currentCity = 0
        currentArea = 0
        currentTown = 0
        mProvince = ""
        mCity = ""
        mArea = ""
        mTown = ""
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mHintDialog?.isShowing == true) {
            mHintDialog?.dismiss()
        }
    }
}

enum class ADDRESS_ENUM {
    TWO, FOUR
}